package com.tg.appcommon.app;


import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.appbase.custom.app.AppStatus;
import com.appbase.custom.app.AppStatusChangeListener;
import com.appbase.custom.app.STATUS;

import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;

public class AppStatusObserver {
    private final String TAG = AppStatusObserver.class.getSimpleName();
    private static AppStatusObserver sInstance;

    // 默认状态是应用进程不存在，应用拉起来之后才会到前台，HOME之后到后台
    @AppStatus
    private int mBackgroundStatus = STATUS.STATUS_NONE;

    private int mCurResumeActivityHC;
    private Set<WeakReference> mWRListener;

    private AppStatusObserver() {
        mWRListener = new HashSet<>();
    }
    private long  backgroundDelayed = 30*1000;
    private Handler mHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==STATUS.STATUS_BACKGROUND_TIMER){
                notifyChange(null,0,msg.what);
            }
        }
    };
    /**
     *
     * 当前App是否在后台
     */
    public boolean isAppInBackground() {
        return mBackgroundStatus == STATUS.STATUS_BACKGROUND;
    }

    /**
     * 应用是否处于前台
     */
    public boolean isAppInForeground() {
        return mBackgroundStatus == STATUS.STATUS_FOREGROUND;
    }

    /**
     * 注册监听
     *
     * @param listener
     */
    public void registerListener(AppStatusChangeListener listener) {
        for (WeakReference w : mWRListener) {
            AppStatusChangeListener l = (AppStatusChangeListener) w.get();
            if (l == listener) {
                return;
            }
        }
        WeakReference<AppStatusChangeListener> w = new WeakReference<>(listener);
        mWRListener.add(w);
    }

    public void unregisterListener(AppStatusChangeListener listener) {
        for (WeakReference w : mWRListener) {
            AppStatusChangeListener l = (AppStatusChangeListener) w.get();
            if (l == listener) {
                w.clear();
                break;
            }
        }
    }

    public static final int EVENT_ON_ACTIVITY_RESUMED = 0;
    public static final int EVENT_ON_ACTIVITY_STOPPED = 1;

    public void onActivityLifecycleEvent(@NonNull Activity activity, int activityNumber, int event) {
        synchronized (AppStatusObserver.class) {
            switch (event) {
                case EVENT_ON_ACTIVITY_RESUMED:
                    mHandler.removeCallbacksAndMessages(null);
                    if (mBackgroundStatus != STATUS.STATUS_FOREGROUND) {
                        if ((activity.hashCode() == mCurResumeActivityHC || mCurResumeActivityHC == 0)) {
                            notifyChange(activity, activityNumber, STATUS.STATUS_FOREGROUND);
                            mBackgroundStatus = STATUS.STATUS_FOREGROUND;
                        } else if (mBackgroundStatus == STATUS.STATUS_BACKGROUND) {
                            notifyChange(activity, activityNumber, STATUS.STATUS_FOREGROUND);
                            mBackgroundStatus = STATUS.STATUS_FOREGROUND;
                        }
                    }
                    this.mCurResumeActivityHC = activity.hashCode();
                    break;
                case EVENT_ON_ACTIVITY_STOPPED:
                    if (activity.hashCode() == mCurResumeActivityHC) {
                        notifyChange(activity, activityNumber, STATUS.STATUS_BACKGROUND);
                        mBackgroundStatus = STATUS.STATUS_BACKGROUND;
                        if (activityNumber == 0){
                            mHandler.sendEmptyMessageDelayed(STATUS.STATUS_BACKGROUND_TIMER,backgroundDelayed);
                        }
                    }
                    break;
            }
        }
    }

    private void notifyChange(Activity activity, int activityNumber, @AppStatus int status) {
        for (WeakReference w : mWRListener) {
            AppStatusChangeListener listener = (AppStatusChangeListener) w.get();
            if (listener != null) {
                listener.onStatusChange(activity, activityNumber, status);
            }
        }
        onStatusChange(status);
    }

    private void onStatusChange(@AppStatus int status) {

    }

    public synchronized static AppStatusObserver getInstance() {
        if (sInstance == null) {
            sInstance = new AppStatusObserver();
        }
        return sInstance;
    }


    public static class AppStatusListener implements AppStatusChangeListener {
        private boolean mCleared = false;

        public void clear() {
            mCleared = true;
        }

        /**
         * 应用状态变化的回调
         */
        public final void onStatusChange(Activity currentActivity, int activityNumber,  @AppStatus int status) {
            if (!mCleared) {
                if (status == STATUS.STATUS_BACKGROUND) {
                    onChangeToBackground();
                }
            }
        }

        public void onChangeToBackground() {

        }
    }
}
